# view/user.py
import os
from datetime import datetime

#导入蓝图类
from flask import Blueprint, request, jsonify, current_app
from werkzeug.utils import secure_filename
# 导入连接数据库的组件
from public.sql_connect import get_connent
# 导入token验证的一块
from public.token import token_required, token_required_with_refresh

# 导入封装的公共模块
from public.goods import good_get_public, good_list_public, comment_list_public,brand_list_public_page,sort_list_public_page


# 创建用户蓝图
good = Blueprint('good_print', __name__)

# 商品列表
@good.route('/list', methods=['GET'])
@token_required
@token_required_with_refresh
def good_list(current_user_id, current_user_account):
    return good_list_public()


# 获取详情
@good.route('/get/<int:good_id>', methods=['GET'])
@token_required
@token_required_with_refresh
def get(current_user_id, current_user_account,good_id):
    return good_get_public(good_id)


# 获取某个商品下的评论
@good.route('/comment_list/<int:good_id>', methods=['GET'])
@token_required
@token_required_with_refresh
def comment_list(current_user_id, current_user_account, good_id):
    return comment_list_public(good_id)


# 获取品牌的列表
@good.route('/brand_list', methods=['GET'])
@token_required
@token_required_with_refresh
def brand_list(current_user_id, current_user_account):
    return brand_list_public_page()


# 品牌管理--查看
@good.route('/brand_view/<int:brand_id>', methods=['GET'])
@token_required
@token_required_with_refresh
def brand_view(current_user_id, current_user_account, brand_id):
    if brand_id is None:
        return jsonify({
            'code': -1,
            'msg': '请提供对应的ID',
            'data': None
        })
    conn = get_connent()
    cursor = conn.cursor(dictionary=True)
    try:
        cursor.execute(
            '''
            SELECT 
                b.id AS brand_id,
                b.name AS brand_name,
                b.nameEn AS brand_name_en,
                b.detail AS brand_detail,
                b.created_at AS brand_created_at,
                b.updated_at AS brand_updated_at,
                CONCAT(
                    '[',
                    GROUP_CONCAT(
                        CONCAT(
                            '{"id":"', g.id, 
                            '","name":"', REPLACE(g.name, '"', '\\"'), 
                            '","price":"', g.price, 
                            '","detail":"', REPLACE(IFNULL(g.detail, ''), '"', '\\"'), '"}'
                        )
                        SEPARATOR ','
                    ),
                    ']'
                ) AS goods_info
            FROM 
                brands b
            LEFT JOIN 
                goods g ON b.id = g.brandId 
            WHERE 
                b.id = %s
            GROUP BY 
                b.id
            ''',
            (brand_id,)
        )
        brand_item = cursor.fetchone()
        return jsonify({
            'code': 0,
            'msg': '品牌详情查看成功',
            'data': {
                'list': brand_item
            }
        })

    except Exception as e:
        conn.rollback()
        return jsonify({
            "code": -1,
            "msg": f"数据库错误: {str(e)}",
            "data": None
        }), 500
    finally:
        cursor.close()
        conn.close()


# 品牌管理--添加
@good.route('/brand_add', methods=['POST'])
@token_required
@token_required_with_refresh
def brand_add(current_user_id, current_user_account):
    data = request.get_json()
    if data is None:
        return jsonify({
            'code': -1,
            'msg': '请提供必要的参数',
            'data': None
        })
    name = data.get('name')
    name_en = data.get('nameEn')
    detail = data.get('detail')
    if name is None or name_en is None:
        return jsonify({
            'code': -1,
            'msg': '请提供必要的参数',
            'data': None
        }),400
    conn = get_connent()
    cursor = conn.cursor(dictionary=True)
    try:
        cursor.execute(
            "INSERT INTO brands (name, nameEn, detail, created_at, updated_at) VALUES (%s, %s, %s, NOW(), NOW())",
            (name, name_en, detail)
        )
        conn.commit()
        if cursor.rowcount != 1:
            return jsonify({
                'code': -1,
                'msg': '数据库未改动，添加失败',
                'data': None
            }), 400
        return jsonify({
            'code': 0,
            'msg': '品牌添加成功',
            'data': {
                'id': cursor.lastrowid,
                'name': name,
                'name_en': name_en,
                'detail': detail,
            }
        })
    except Exception as e:
        conn.rollback()
        return jsonify({
            "code": -1,
            "msg": f"数据库错误: {str(e)}",
            "data": None
        }), 500
    finally:
        cursor.close()
        conn.close()


# 品牌管理--修改
@good.route('/brand_update/<int:brand_id>', methods=['PUT'])
@token_required
@token_required_with_refresh
def brand_update(current_user_id, current_user_account, brand_id):
    data = request.get_json()
    if data is None:
        return jsonify({
            'code': -1,
            'msg': '请提供请求参数',
            'data': None
        })
    if brand_id is None:
        return jsonify({
            'code': -1,
            'msg': '请提供对应的ID',
            'data': None
        })
    name = data.get('name')
    name_en = data.get('nameEn')
    detail = data.get('detail')
    if name is None or name_en is None:
        return jsonify({
            'code': -1,
            'msg': '请提供必要的参数',
            'data': None
        }), 400
    conn = get_connent()
    cursor = conn.cursor(dictionary=True)
    try:
        cursor.execute(
            "UPDATE brands SET name = %s, nameEn = %s, detail = %s, updated_at = NOW() WHERE id = %s",
            (name, name_en, detail, brand_id)
        )
        conn.commit()
        if cursor.rowcount != 1:
            return jsonify({
                'code': -1,
                'msg': '数据库未改动，修改失败',
                'data': None
            }), 400
        return jsonify({
            'code': 0,
            'msg': '品牌修改成功',
            'data': {
                'id': brand_id,
                'name': name,
                'name_en': name_en,
                'detail': detail,
            }
        })
    except Exception as e:
        conn.rollback()
        return jsonify({
            "code": -1,
            "msg": f"数据库错误: {str(e)}",
            "data": None
        }), 500
    finally:
        cursor.close()
        conn.close()


# 品牌管理--删除
@good.route('/brand_delete/<int:brand_id>', methods=['DELETE'])
@token_required
@token_required_with_refresh
def brand_delete(current_user_id, current_user_account, brand_id):
    if brand_id is None:
        return jsonify({
            'code': -1,
            'msg': '请提供删除对象的ID',
            'data': None
        })
    conn = get_connent()
    cursor = conn.cursor(dictionary=True)
    try:
        cursor.execute(
            "DELETE FROM brands WHERE id = %s",
            (brand_id,)
        )
        conn.commit()
        if cursor.rowcount != 1:
            return jsonify({
                'code': -1,
                'msg': '数据库未改动，删除失败',
                'data': None
            }), 400
        return jsonify({
            'code': 0,
            'msg': '品牌删除成功',
            'data': {
                'id': brand_id,
            }
        })
    except Exception as e:
        conn.rollback()
        return jsonify({
            "code": -1,
            "msg": f"数据库错误: {str(e)}",
            "data": None
        }), 500
    finally:
        cursor.close()
        conn.close()



# 获取分类的列表
@good.route('/sort_list', methods=['GET'])
@token_required
@token_required_with_refresh
def sort_list(current_user_id, current_user_account):
    return sort_list_public_page()



# 分类管理--查看
@good.route('/sort_view/<int:sort_id>', methods=['GET'])
@token_required
@token_required_with_refresh
def sort_view(current_user_id, current_user_account, sort_id):
    if sort_id is None:
        return jsonify({
            'code': -1,
            'msg': '请提供对应的ID',
            'data': None
        })
    conn = get_connent()
    cursor = conn.cursor(dictionary=True)
    try:
        cursor.execute(
            '''
            SELECT s.id         AS sort_id,
                   s.name       AS sort_name,
                   s.nameEn     AS sort_name_en,
                   s.detail     AS sort_detail,
                   s.created_at AS sort_created_at,
                   s.updated_at AS sort_updated_at,
                   CONCAT(
                           '[',
                           GROUP_CONCAT(
                                   CONCAT(
                                           '{"id":"', g.id,
                                           '","name":"', REPLACE(g.name, '"', '\\"'),
                                           '","price":"', g.price,
                                           '","detail":"', REPLACE(IFNULL(g.detail, ''), '"', '\\"'), '"}'
                                   ) SEPARATOR ','
                           ),
                           ']'
                   )            AS goods_info
            FROM sorts s
                     LEFT JOIN
                 goods g ON s.id = g.sort_id
            WHERE s.id = %s
            GROUP BY s.id
            ''',
            (sort_id,)
        )
        sort_item = cursor.fetchone()
        return jsonify({
            'code': 0,
            'msg': '分类详情查看成功',
            'data': {
                'list': sort_item
            }
        })

    except Exception as e:
        conn.rollback()
        return jsonify({
            "code": -1,
            "msg": f"数据库错误: {str(e)}",
            "data": None
        }), 500
    finally:
        cursor.close()
        conn.close()



# 分类管理--添加
@good.route('/sort_add', methods=['POST'])
@token_required
@token_required_with_refresh
def sort_add(current_user_id, current_user_account):
    data = request.get_json()
    if data is None:
        return jsonify({
            'code': -1,
            'msg': '请提供必要的参数',
            'data': None
        })
    name = data.get('name')
    name_en = data.get('nameEn')
    detail = data.get('detail')
    if name is None or name_en is None:
        return jsonify({
            'code': -1,
            'msg': '请提供必要的参数',
            'data': None
        }), 400
    conn = get_connent()
    cursor = conn.cursor(dictionary=True)
    try:
        cursor.execute(
            "INSERT INTO sorts (name, nameEn, detail, created_at, updated_at) VALUES (%s, %s, %s, NOW(), NOW())",
            (name, name_en, detail)
        )
        conn.commit()
        if cursor.rowcount != 1:
            return jsonify({
                'code': -1,
                'msg': '数据库未改动，添加失败',
                'data': None
            }), 400
        return jsonify({
            'code': 0,
            'msg': '分类添加成功',
            'data': {
                'id': cursor.lastrowid,
                'name': name,
                'name_en': name_en,
                'detail': detail,
            }
        })
    except Exception as e:
        conn.rollback()
        return jsonify({
            "code": -1,
            "msg": f"数据库错误: {str(e)}",
            "data": None
        }), 500
    finally:
        cursor.close()
        conn.close()



# 分类管理--修改
@good.route('/sort_update/<int:sort_id>', methods=['PUT'])
@token_required
@token_required_with_refresh
def sort_update(current_user_id, current_user_account, sort_id):
    data = request.get_json()
    if data is None:
        return jsonify({
            'code': -1,
            'msg': '请提供请求参数',
            'data': None
        })
    if sort_id is None:
        return jsonify({
            'code': -1,
            'msg': '请提供对应的ID',
            'data': None
        })
    name = data.get('name')
    name_en = data.get('nameEn')
    detail = data.get('detail')
    if name is None or name_en is None:
        return jsonify({
            'code': -1,
            'msg': '请提供必要的参数',
            'data': None
        }), 400
    conn = get_connent()
    cursor = conn.cursor(dictionary=True)
    try:
        cursor.execute(
            "UPDATE sorts SET name = %s, nameEn = %s, detail = %s, updated_at = NOW() WHERE id = %s",
            (name, name_en, detail, sort_id)
        )
        conn.commit()
        if cursor.rowcount != 1:
            return jsonify({
                'code': -1,
                'msg': '数据库未改动，修改失败',
                'data': None
            }), 400
        return jsonify({
            'code': 0,
            'msg': '分类修改成功',
            'data': {
                'id': sort_id,
                'name': name,
                'name_en': name_en,
                'detail': detail,
            }
        })
    except Exception as e:
        conn.rollback()
        return jsonify({
            "code": -1,
            "msg": f"数据库错误: {str(e)}",
            "data": None
        }), 500
    finally:
        cursor.close()
        conn.close()



# 分类管理--删除
@good.route('/sort_delete/<int:sort_id>', methods=['DELETE'])
@token_required
@token_required_with_refresh
def sort_delete(current_user_id, current_user_account, sort_id):
    if sort_id is None:
        return jsonify({
            'code': -1,
            'msg': '请提供删除对象的ID',
            'data': None
        })
    conn = get_connent()
    cursor = conn.cursor(dictionary=True)
    try:
        # 先检查是否有商品关联该分类
        cursor.execute("SELECT COUNT(*) FROM goods WHERE sort_id = %s", (sort_id,))
        goods_count = cursor.fetchone()['COUNT(*)']
        if goods_count > 0:
            return jsonify({
                'code': -1,
                'msg': '该分类下存在关联商品，无法删除',
                'data': None
            }), 400

        cursor.execute("DELETE FROM sorts WHERE id = %s", (sort_id,))
        conn.commit()
        if cursor.rowcount != 1:
            return jsonify({
                'code': -1,
                'msg': '数据库未改动，删除失败',
                'data': None
            }), 400
        return jsonify({
            'code': 0,
            'msg': '分类删除成功',
            'data': {
                'id': sort_id,
            }
        })
    except Exception as e:
        conn.rollback()
        return jsonify({
            "code": -1,
            "msg": f"数据库错误: {str(e)}",
            "data": None
        }), 500
    finally:
        cursor.close()
        conn.close()



# 成交额计算
@good.route('/all_money', methods=['GET'])
@token_required
@token_required_with_refresh
def all_money(current_user_id, current_user_account):
    conn = get_connent()
    cursor = conn.cursor(dictionary=True)
    try:
        # 正确的SQL查询，计算总成交额
        # ​​待付款（Pending）、处理中（Processing）、已发货（Shipped）、待评价（Commenting）、已完成（Done）、已取消（Canceled）
        cursor.execute(
            '''
            SELECT SUM(ug.count * g.price) as total_money
            FROM user_goods ug
                     LEFT JOIN goods g ON g.id = ug.good_id
            WHERE ug.status != 'Pending' AND ug.status != 'Canceled' -- 假设有状态字段表示已完成订单
            '''
        )
        result = cursor.fetchone()
        all_money = result['total_money'] if result['total_money'] is not None else 0

        return jsonify({
            'code': 0,
            'msg': '成交额请求成功',
            'data': {
                'all_money': float(all_money)  # 确保金额是浮点数
            }
        })
    except Exception as e:
        conn.rollback()
        return jsonify({
            "code": -1,
            "msg": f"数据库错误: {str(e)}",
            "data": None
        }), 500
    finally:
        cursor.close()
        conn.close()



# 商品种类总数
@good.route('/good_count', methods=['GET'])
@token_required
@token_required_with_refresh
def good_count(current_user_id, current_user_account):
    conn = get_connent()
    cursor = conn.cursor(dictionary=True)
    try:
        cursor.execute(
            "SELECT COUNT(id) as total FROM goods",
        )
        good_count_date = cursor.fetchone()['total']
        return jsonify({
            'code': 0,
            'msg': '商品种类总数请求成功',
            'data': {
                'good_count': good_count_date,
            }
        })
    except Exception as e:
        conn.rollback()
        return jsonify({
            "code": -1,
            "msg": f"数据库错误: {str(e)}",
            "data": None
        }), 500
    finally:
        cursor.close()
        conn.close()



# 订单总数
@good.route('/order_count', methods=['GET'])
@token_required
@token_required_with_refresh
def order_count(current_user_id, current_user_account):
    conn = get_connent()
    cursor = conn.cursor(dictionary=True)
    try:
        cursor.execute(
            "SELECT COUNT(id) as total FROM user_goods",
        )
        order_count_date = cursor.fetchone()['total']
        return jsonify({
            'code': 0,
            'msg': '订单总数',
            'data': {
                'order_count': order_count_date,
            }
        })
    except Exception as e:
        conn.rollback()
        return jsonify({
            "code": -1,
            "msg": f"数据库错误: {str(e)}",
            "data": None
        }), 500
    finally:
        cursor.close()
        conn.close()



# 当天的订单总数
@good.route('/order_count_today', methods=['GET'])
@token_required
@token_required_with_refresh
def order_count_today(current_user_id, current_user_account):
    conn = get_connent()
    cursor = conn.cursor(dictionary=True)
    try:
        # 正确的SQL查询，计算当天的订单总数
        cursor.execute(
            "SELECT COUNT(id) as total FROM user_goods WHERE DATE(created_at) = CURDATE()",
        )
        result = cursor.fetchone()
        order_count_today = result['total'] if result else 0

        return jsonify({
            'code': 0,
            'msg': '当天订单总数',
            'data': {
                'order_count': order_count_today,
            }
        })
    except Exception as e:
        conn.rollback()
        return jsonify({
            "code": -1,
            "msg": f"数据库错误: {str(e)}",
            "data": None
        }), 500
    finally:
        cursor.close()
        conn.close()



# 用户总数
@good.route('/user_count', methods=['GET'])
@token_required
@token_required_with_refresh
def user_count(current_user_id, current_user_account):
    conn = get_connent()
    cursor = conn.cursor(dictionary=True)
    try:
        cursor.execute(
            "SELECT COUNT(id) as total FROM users"
        )
        total_count = cursor.fetchone()['total']
        return jsonify({
            'code': 0,
            "msg": "用户总数请求成功",
            "data": {
                'total_count': total_count,
            }
        })

    except Exception as e:
        conn.rollback()
        return jsonify({
            "code": -1,
            "msg": f"数据库错误: {str(e)}",
            "data": None
        }), 500
    finally:
        cursor.close()
        conn.close()



# 商品销量统计前10名
@good.route('/salesCount_rank')
@token_required
@token_required_with_refresh
def sales_count_rank(current_user_id, current_user_account):
    conn = get_connent()
    cursor = conn.cursor(dictionary=True)
    try:
        cursor.execute(
            "SELECT id, salesCount, name FROM goods ORDER BY salesCount DESC LIMIT 10",
        )
        result = cursor.fetchall()
        return jsonify({
            'code': 0,
            "msg": "商品销量前10名",
            "data": {
                "top_10": result,
            }
        })

    except Exception as e:
        conn.rollback()
        return jsonify({
            "code": -1,
            "msg": f"数据库错误: {str(e)}",
            "data": None
        }), 500
    finally:
        cursor.close()
        conn.close()


